package 链表;

/**
 * @author: 大怪
 * @email: 962527441@qq.com
 */

/**
 * 题目：
 * 给定一个单链表 L 的头节点 head ，单链表 L 表示为：
 *  L0 → L1 → … → Ln-1 → Ln 
 * 请将其重新排列后变为：
 * L0 → Ln → L1 → Ln-1 → L2 → Ln-2 → …
 * 不能只是单纯的改变节点内部的值，而是需要实际的进行节点交换。
 *
 * 示例 1:
 * 输入: head = [1,2,3,4]
 * 输出: [1,4,2,3]
 */
public class 重排链表 {

    public class ListNode {
        int val;
        ListNode next;
        ListNode() {}
        ListNode(int val) { this.val = val; }
        ListNode(int val, ListNode next) { this.val = val; this.next = next; }
    }

    class Solution {
        public void reorderList(ListNode head) {
            if (head == null || head.next == null) {
                return;
            }
            ListNode listNode = new ListNode(0);
            listNode.next = head;
            ListNode fast = listNode;
            ListNode slow = listNode;
            while (fast != null && fast.next != null) {
                fast = fast.next.next;
                slow = slow.next;
            }

            ListNode half = slow.next;
            slow.next = null;
            ListNode res_half = reverseList(half);
            ListNode cur = listNode.next;
            while (res_half != null) {
                ListNode tmp = cur.next;
                cur.next = res_half;
                cur = cur.next;
                res_half = res_half.next;
                cur.next = tmp;
                cur = cur.next;
            }


        }


        public ListNode reverseList(ListNode head) {
            ListNode a = null;
            while (head != null) {
                ListNode tmp = head.next;
                head.next = a;
                a = head;
                head = tmp;

            }

            return a;
        }
    }
}
